package services

import (
	"errors"
	"fmt"
	database "hft/Database"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	"hft/Http/Models/request"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
	"hft/tools/phone/api"
	"regexp"

	"gorm.io/gorm"
)

type LouPan struct{}

func (*LouPan) CreateLouPan(LouPanInfo *request.LouPan, claims tools.BaseClaims) (err error) {

	// var account *admin.Account

	// var region *admin.Region

	// err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	// if err != nil {
	// 	return errors.New("无该账号信息")
	// }

	// err = global.OC_DB.First(&region, LouPanInfo.Region).Error

	// if err != nil {
	// 	return errors.New("无该地区信息")
	// }

	// match, err := regexp.MatchString(fmt.Sprintf("(%v)", account.RegionLink), region.Link)

	// if err != nil {
	// 	return errors.New("未知错误500")
	// }

	// if !match {
	// 	return errors.New("无权添加该区域楼盘")
	// }

	// belongName := utils.AccountBelongRegion(fmt.Sprintf("%v%v,", region.Link, region.ID), global.OC_DB)

	// var tags []*admin.CommonTag

	// var dis []*admin.Disadvantage

	// var property []*admin.Property

	// var roomType []*admin.RoomType

	// var tese []*admin.LouPanTeSe

	// err = global.OC_DB.Find(&tags, LouPanInfo.Tag).Error

	// if err != nil {
	// 	return errors.New(err.Error())
	// }
	// err = global.OC_DB.Find(&dis, LouPanInfo.Disadvantage).Error

	// if err != nil {
	// 	return errors.New(err.Error())
	// }

	// err = global.OC_DB.Find(&property, LouPanInfo.PropertyUse).Error

	// if err != nil {
	// 	return errors.New(err.Error())
	// }

	// err = global.OC_DB.Find(&roomType, LouPanInfo.RoomType).Error

	// if err != nil {
	// 	return errors.New(err.Error())
	// }

	// err = global.OC_DB.Find(&tese, LouPanInfo.Tese).Error

	// if err != nil {
	// 	return errors.New(err.Error())
	// }

	// err = global.OC_DB.Transaction(func(tx *gorm.DB) error {

	// 	// 创建完毕后添加分机号码

	// 	city, _ := utils.GetRegionBelongCity(fmt.Sprintf("%v%v,", region.Link, region.ID))

	// 	// 查出账号

	// 	var manager *admin.Account
	// 	var managerRegion *admin.Region

	// 	err = global.OC_DB.First(&managerRegion, city).Error

	// 	if err != nil {
	// 		return errors.New("该城市不存在")
	// 	}

	// 	if managerRegion.ManageId == 0 {
	// 		return errors.New("该地区还未有管理人")
	// 	}

	// 	err = global.OC_DB.First(&manager, managerRegion.ManageId).Error

	// 	if err != nil {
	// 		return errors.New("管理者账号不存在或者已禁用")
	// 	}

	// 	// 获取当前的最大分机号

	// 	result, err := global.OC_REDIS.Get("phone_max").Result()

	// 	if err != nil {
	// 		return errors.New("未知错误500")
	// 	}

	// 	var newDn, _ = strconv.Atoi(result)

	// 	newDn = newDn + 1

	// 	var dnBroker = &admin.DNBroker{Dn: strconv.Itoa(newDn), Tel: ""}

	// 	res := tx.Where("dn = ?", newDn).FirstOrCreate(&dnBroker)

	// 	if res.RowsAffected == 0 {
	// 		return errors.New("该分机号已存在")
	// 	}

	// 	if res.Error != nil {
	// 		return errors.New("未知错误500")
	// 	}

	// 	loupan_dao.AddAudio(strconv.Itoa(newDn), LouPanInfo.Name)

	// 	var phoneList []*model.Row

	// 	phoneList = append(phoneList, &model.Row{Dn: strconv.Itoa(newDn), Tel: manager.Phone, TransType: "rnd"})

	// 	code := api.PhoneVirtual.AddOrEditPhone(phoneList)

	// 	if code != "0" {
	// 		return errors.New("添加经纪人电话失败")
	// 	}

	// 	var louPan = &admin.LouPan{
	// 		Base: database.Base{
	// 			Sort: LouPanInfo.Sort,
	// 		},
	// 		FirstWord:      tools.PinYin(LouPanInfo.Name),
	// 		MaxArea:        LouPanInfo.MaxArea,
	// 		MinArea:        LouPanInfo.MinArea,
	// 		Name:           LouPanInfo.Name,
	// 		Cover:          LouPanInfo.Cover,
	// 		RegionLink:     fmt.Sprintf("%v%v,", region.Link, LouPanInfo.Region),
	// 		Region:         LouPanInfo.Region,
	// 		BelongName:     belongName,
	// 		Years:          LouPanInfo.Years,
	// 		Furnish:        LouPanInfo.Furnish,
	// 		Address:        LouPanInfo.Address,
	// 		ReferencePrice: LouPanInfo.ReferencePrice,
	// 		Grounding:      LouPanInfo.Grounding,
	// 		Longitude:      LouPanInfo.Longitude,
	// 		Latitude:       LouPanInfo.Latitude,
	// 		IsAudit:        0,
	// 		Status:         LouPanInfo.Status,
	// 		SellLouPanInfo: admin.SellLouPanInfo{
	// 			OpenTime:    LouPanInfo.OpenTime,
	// 			GetRoomTime: LouPanInfo.GetRoomTime,
	// 			Developer:   LouPanInfo.Developer,
	// 			License:     LouPanInfo.License,
	// 			SellPhone:   strconv.Itoa(newDn),
	// 		},
	// 		LouPanArea: admin.LouPanArea{
	// 			FloorArea:       LouPanInfo.FloorArea,
	// 			BuildArea:       LouPanInfo.BuildArea,
	// 			BuildNum:        LouPanInfo.BuildNum,
	// 			UserNum:         LouPanInfo.UserNum,
	// 			ParkingSpace:    LouPanInfo.ParkingSpace,
	// 			VolumeRate:      LouPanInfo.VolumeRate,
	// 			GreeningRate:    LouPanInfo.GreeningRate,
	// 			PropertyCost:    LouPanInfo.PropertyCost,
	// 			PropertyCompany: LouPanInfo.PropertyCompany,
	// 		},
	// 	}

	// 	res = tx.Where("name = ? AND region = ?", louPan.Name, louPan.Region).FirstOrCreate(&louPan)

	// 	if res.Error != nil {
	// 		return errors.New("未知错误500")
	// 	}

	// 	if res.RowsAffected == 0 {
	// 		return errors.New("该楼盘已存在")
	// 	}

	// 	tx.Model(&admin.DNBroker{}).Where("dn = ?", newDn).Updates(map[string]interface{}{
	// 		"region":       louPan.Region,
	// 		"lou_pan_name": louPan.Name,
	// 	})

	// 	// 创建完成之后 redis+1

	// 	global.OC_REDIS.Incr("phone_max")

	// 	tx.Model(&louPan).Association("Tags").Replace(&tags)
	// 	tx.Model(&louPan).Association("Properties").Replace(&property)
	// 	tx.Model(&louPan).Association("Disadvantage").Replace(&dis)
	// 	tx.Model(&louPan).Association("RoomType").Replace(&roomType)
	// 	tx.Model(&louPan).Association("TeSe").Replace(&tese)

	// 	return nil
	// })

	return err
}

func (*LouPan) GetLouPanList(paginate *request.LouPaPaginate, claims tools.BaseClaims) (data *utils.Page, err error) {

	var account *admin.Account

	var louPanList []*admin.LouPan

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("无该账号信息")
	}

	err = global.OC_DB.Scopes(dao.LouPanDao.GetLouPanList(fmt.Sprintf("%v%%", account.RegionLink), paginate, global.OC_DB)).Find(&louPanList).Offset(-1).Limit(-1).Count(&paginate.Total).Error

	if err != nil {
		return nil, errors.New("未知错误500")
	}

	for _, v := range louPanList {
		v.Cover = global.OC_CONFIG.AliyunOSS.BucketUrl + v.Cover
		v.SellLouPanInfo.SellPhone = global.OC_CONFIG.Phone.Account + "," + v.SellLouPanInfo.SellPhone
	}

	paginate.Data = louPanList

	return &paginate.Page, nil
}

func (*LouPan) EditLouPan(LouPanInfo *request.LouPan, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	var region *admin.Region

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("无该账号信息")
	}

	global.OC_DB.First(&region, LouPanInfo.Region)

	if err != nil {
		return errors.New("无该地区信息")
	}

	match, err := regexp.MatchString(fmt.Sprintf("(%v)", account.RegionLink), region.Link)

	if err != nil {
		return errors.New("未知错误500")
	}

	if !match {
		return errors.New("无权添加该区域楼盘")
	}

	belongName := utils.AccountBelongRegion(fmt.Sprintf("%v%v,", region.Link, region.ID), global.OC_DB)

	fmt.Println(belongName)

	var tags []*admin.CommonTag

	var dis []*admin.Disadvantage

	var property []*admin.Property

	var roomType []*admin.RoomType

	var tese []*admin.LouPanTeSe

	err = global.OC_DB.Find(&tags, LouPanInfo.Tag).Error

	if err != nil {
		return errors.New(err.Error())
	}
	err = global.OC_DB.Find(&dis, LouPanInfo.Disadvantage).Error

	if err != nil {
		return errors.New(err.Error())
	}

	err = global.OC_DB.Find(&property, LouPanInfo.PropertyUse).Error

	if err != nil {
		return errors.New(err.Error())
	}

	err = global.OC_DB.Find(&roomType, LouPanInfo.RoomType).Error

	if err != nil {
		return errors.New(err.Error())
	}

	err = global.OC_DB.Find(&tese, LouPanInfo.Tese).Error

	if err != nil {
		return errors.New(err.Error())
	}

	err = global.OC_DB.Transaction(func(tx *gorm.DB) error {

		var louPan = &admin.LouPan{
			Base: database.Base{
				ID:   uint(LouPanInfo.ID),
				Sort: LouPanInfo.Sort,
			},
			FirstWord:      tools.PinYin(LouPanInfo.Name),
			MaxArea:        LouPanInfo.MaxArea,
			MinArea:        LouPanInfo.MinArea,
			Name:           LouPanInfo.Name,
			Cover:          LouPanInfo.Cover,
			RegionLink:     fmt.Sprintf("%v%v,", region.Link, LouPanInfo.Region),
			Region:         LouPanInfo.Region,
			BelongName:     belongName,
			Years:          LouPanInfo.Years,
			Address:        LouPanInfo.Address,
			Furnish:        LouPanInfo.Furnish,
			ReferencePrice: LouPanInfo.ReferencePrice,
			Grounding:      LouPanInfo.Grounding,
			Longitude:      LouPanInfo.Longitude,
			Latitude:       LouPanInfo.Latitude,
			IsAudit:        0,
			Status:         LouPanInfo.Status,
		}
		res := tx.Where("id = ?", LouPanInfo.ID).Updates(&louPan)
		tx.Model(&admin.LouPan{}).Where("id = ?", LouPanInfo.ID).Updates(map[string]interface{}{"grounding": LouPanInfo.Grounding})
		tx.Model(&admin.SellLouPanInfo{}).Where("lou_pan_id = ?", LouPanInfo.ID).Updates(admin.SellLouPanInfo{
			OpenTime:    LouPanInfo.OpenTime,
			GetRoomTime: LouPanInfo.GetRoomTime,
			Developer:   LouPanInfo.Developer,
			License:     LouPanInfo.License,
		})
		tx.Model(&admin.LouPanArea{}).Where("lou_pan_id = ?", LouPanInfo.ID).Updates(admin.LouPanArea{
			FloorArea:       LouPanInfo.FloorArea,
			BuildArea:       LouPanInfo.BuildArea,
			BuildNum:        LouPanInfo.BuildNum,
			UserNum:         LouPanInfo.UserNum,
			ParkingSpace:    LouPanInfo.ParkingSpace,
			VolumeRate:      LouPanInfo.VolumeRate,
			GreeningRate:    LouPanInfo.GreeningRate,
			PropertyCost:    LouPanInfo.PropertyCost,
			PropertyCompany: LouPanInfo.PropertyCompany,
		})
		if res.Error != nil {
			return errors.New("未知错误500")
		}

		tx.Model(&louPan).Association("Tags").Replace(&tags)
		tx.Model(&louPan).Association("Properties").Replace(&property)
		tx.Model(&louPan).Association("Disadvantage").Replace(&dis)
		tx.Model(&louPan).Association("RoomType").Replace(&roomType)
		tx.Model(&louPan).Association("TeSe").Replace(&tese)

		return nil
	})

	return nil
}

func (*LouPan) GetLouPanInfo(id int, claims tools.BaseClaims) (data *admin.LouPan, err error) {

	var account *admin.Account

	var louPanInfo *admin.LouPan

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("无该账号信息")
	}

	res := global.OC_DB.Scopes(dao.LouPanDao.LouPanPreload(global.OC_DB)).First(&louPanInfo, id)

	if res.Error != nil {
		return nil, errors.New("未知错误500")
	}

	if res.RowsAffected == 0 {
		return nil, errors.New("楼盘信息不存在")
	}

	match, err := regexp.MatchString(fmt.Sprintf("(%v)", account.RegionLink), louPanInfo.RegionLink)

	if !match {
		return nil, errors.New("你无权编辑该楼盘")
	}

	louPanInfo.SellLouPanInfo.SellPhone = global.OC_CONFIG.Phone.Account + "-" + louPanInfo.SellLouPanInfo.SellPhone

	return louPanInfo, nil
}

func (*LouPan) Delete(ids []int, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("该账号信息不存在")
	}

	var lous []*admin.LouPan

	global.OC_DB.Preload("SellLouPanInfo").Find(&lous, ids)

	res := utils.IsThisLouBelongThisAccount(lous, account.RegionLink)

	if !res {
		return errors.New("你无权修改楼盘信息")
	}

	err = global.OC_DB.Transaction(func(tx *gorm.DB) error {

		err = tx.Model(&admin.LouPan{}).Unscoped().Delete(&lous).Error

		if err != nil {
			return errors.New("删除楼盘失败")
		}

		var dns []string

		for _, v := range lous {

			if v.SellLouPanInfo.SellPhone != "" {
				dns = append(dns, v.SellLouPanInfo.SellPhone)
			}

		}

		err = tx.Where("dn IN ?", dns).Unscoped().Delete(&admin.DNBroker{}).Error

		if err != nil {
			return errors.New("删除分机号失败500")
		}

		code := api.PhoneVirtual.DeletePhone(dns)

		if code != "0" {
			return errors.New("分机号不存在")
		}

		return nil
	})

	return err

}

var LouPanService = new(LouPan)
